/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-07-18
 * Time: 16:37
 */
public class Test {
    //给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
    //实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
    //其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
    //最终再汇总两个和, 进行相加
    //记录程序的执行时间.
    private static long sum1 = 0;
    private static long sum2 = 0;

    public static void main1(String[] args) throws InterruptedException {
        int[] arr = new int[10000000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < arr.length; i += 2) {
                sum1 += arr[i];
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 1; i < arr.length; i += 2) {
                sum2 += arr[i];
            }
        });
        long start = System.currentTimeMillis();
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println(sum1 + sum2);
        System.out.println((end - start) + "ms");
    }

    //在子线程执行完毕后再执行主线程代码
    //题目内容：
    //有20个线程，需要同时启动。
    //每个线程按0-19的序号打印，如第一个线程需要打印0
    //请设计代码，在main主线程中，等待所有子线程执行完后，再打印 ok
    public static void main(String[] args) throws InterruptedException {
        Thread t0 = new Thread(() -> {
            System.out.println(0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t1 = new Thread(() -> {
            System.out.println(1);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t2 = new Thread(() -> {
            System.out.println(2);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t0.start();
        t1.start();
        t2.start();
        t0.join();
        t1.join();
        t2.join();
        System.out.println("ok");
    }
}
